// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
//游戏逻辑
cc.Class({
    extends: cc.Component,

    properties: {
        gameAera: cc.Node,
        cake_preab: cc.Node,
        isInited: false,
        posList: [],
        btnWidth: 0,
        btnHeight: 0,
        btn_sell: null,
        cake_altas: null,
        panelBase: null,
        //要被回收的node
        resolveNode:null,
        //
      //  btn_sell_pos:null,
    },
    init(gameAera, prefab, btn_sell) {
        if (this.isInited)
            return;
        this.resolveNode = null;
        this.gameAera = gameAera;
        for (let i = 0; i < this.gameAera.childrenCount; ++i) {
            let child = this.gameAera.children[i]
            if (child && child.name.indexOf("pos") > -1) {
                this.posList.push(cc.v2(child.x, child.y));
                this.btnWidth = child.width;
                this.btnHeight = child.height;
            }
        }
        this.cake_altas = this.getCakeList();
        this.panelBase = this.node.getComponent("panelBase")
        this.btn_sell = btn_sell;

        this.cake_preab = prefab;
        this.cake_preab.parent = this.gameAera;

        this.btn_sell.active = false;
        cc.tg.eventCenter.addEvent("updateCake",()=>{
            let list = cc.tg.cakeRoom.cakeList;
            if (list.length > 0) {
                for (let i = 0; i < list.length; ++i) {
                    if (!list[i].itemCount)
                        continue;
                   
                    this.onBuyItem(cc.tg.cakeRoom.getCakeDataByItemCode(list[i].itemCode), 1);
                    cc.tg.cakeRoom.getIndex(list[i].itemCode)
                }
            }
        })

        cc.tg.eventCenter.addEvent("onResolveSucess",()=>{
            this.resolveNode.destroy();
            this.resolveNode = null;
        });

        //**坐标转换等效 */
        /*
        let btn_sell_pos = cc.v2(this.btn_sell.x - this.gameAera.x,this.btn_sell.y - this.gameAera.y);
        cc.log(btn_sell_pos);

        let pos = this.btn_sell.convertToWorldSpaceAR(cc.v2(0,0));
        let s_pos = this.gameAera.convertToNodeSpaceAR(pos);
        cc.log(s_pos);

        */

        // this.btn_sell_pos = this.gameAera.convertToNodeSpaceAR(this.btn_sell.convertToWorldSpaceAR(cc.v2(0,0)));
        // cc.log(this.btn_sell_pos);
        this.isInited = true;
    },


    //点击快速购买
    onBuyItem(data, count) {
        if (!data)
            return;

       // let data = cc.tg.cakeRoom.getCakeDataByItemCode(itemCode);
        let cake = cc.instantiate(this.cake_preab);
        let index = data.pos == null ? cc.tg.cakeRoom.getIndex() : data.pos;

        cake.parent = this.gameAera;
      //  cc.log(data)
        cake.name = "cake_" + index;
        cake.rank = data.rank;
        cake.setPosition(this.posList[index]);
        this.initcake(cake, data);
        cake.active = true;
    },

    onFastBack() {

    },


    initcake(node, data) {
        if (!node || !data)
            return;
      
        this._updateCake(node,data);
        node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCanel, this);
    },

    _updateCake(node,data){
        this.panelBase.updateInfo(node.getChildByName("cake"), this.cake_altas.getSpriteFrame("cake_" + data["rank"]), cc.Sprite);
        this.panelBase.updateInfo(node.getChildByName("count"), data["count"], cc.Label);
        this.panelBase.updateInfo(node.getChildByName("coin"), "", cc.Label);
    },

    onTouchStart(e) {
      //  cc.log(e);
        let node = e.target;
        node.scale = 1.1;
        // let pos =
        this.btn_sell.active = true ;
    },
    onTouchMove(e) {
      //  cc.log(e);
        let node = e.target;
        let location = this.gameAera.convertToNodeSpaceAR(e.getLocation());
        //   cc.log(location);
        this.judgePosition(node, location, false);

    },

    onTouchEnd(e) {
      //  cc.log(e);
        let node = e.target;
        node.scale = 1;
        let location = this.gameAera.convertToNodeSpaceAR(e.getLocation());
        //   cc.log(location);
        this.judgePosition(node, location, true);
        this.btn_sell.active = false;
    },


    onTouchCanel(e) {
        //cc.log(e);
        let node = e.target;
        node.scale = 1;
        let location = this.gameAera.convertToNodeSpaceAR(e.getLocation());
        //  
        this.judgePosition(node, location, true);
        this.btn_sell.active = false;
    },
    //判断坐标
    // node 选中的蛋糕
    // location 蛋糕的位置
    // isEnd  是否松手或者移动到屏幕外
    judgePosition(node, location, isEnd = false) {
        if (!node)
            return;
        //cc.log(location);
        let aeraWidth = this.gameAera.width;
        let aeraHieght = this.gameAera.height;
        let offsetLeft = location.x - node.width / 2 + aeraWidth / 2;
        let offsetRight = location.x + node.width / 2 - aeraWidth / 2;
        let offsetTop = location.y + node.height / 2 - aeraHieght / 2;
        let offsetButtom = location.y - node.height / 2 + aeraHieght / 2;
        let index = node.name.indexOf("_")
        let pos = parseInt(node.name.substring(index+1));
     //   let rank = node.rank;
        if (isEnd) {
            //判断是否回收

          //  let  ret = node.getBoundingBox().rectIntersectsRect(this.btn_sell.getBoundingBox())
           // let ret = cc.rectIntersectsRect(node.getBoundingBox(),this.btn_sell.getBoundingBox())
            let ret = node.getBoundingBox().intersects(this.btn_sell.getBoundingBox())
            if(ret)
            {
                //回收 
               // node.destroy();
               this.resolveNode = node;
             
                cc.tg.gameLogic.toResolve(pos);
                return ;
            }

            // cc.log(node.getBoundingBox());
            // cc.log(this.btn_sell.getBoundingBox());


            if (offsetLeft <= 0) {
                location.x = node.width / 2 - aeraWidth / 2;
            }

            if (offsetRight >= 0) {
                location.x = aeraWidth / 2 - node.width / 2
            }

            if (offsetTop >= 0) {
                location.y = aeraHieght / 2 - node.height / 2
            }

            if (offsetButtom <= 0) {
                location.y = node.height / 2 - aeraHieght / 2
            }
            //是否判断有错误
            let isJudgeRight = false
            for (let i = 0; i < this.posList.length; ++i) {
                let xOffset = Math.abs(location.x - this.posList[i].x);
                let yOffset = Math.abs(location.y - this.posList[i].y);
               // cc.log(xOffset + " " + yOffset);
                if (xOffset <= this.btnWidth / 2  && yOffset <= this.btnHeight / 2) {
                    cc.tg.cakeRoom.updateLevel( i,pos);
                    isJudgeRight = true;
                    return;
                }
            }
            if(!isJudgeRight)
            {
                //判断错误就返回原来的位置
                cc.tg.cakeRoom.updateLevel( pos,pos);
            }

        }
        else {

            //
            node.setPosition(location);
            //屏幕边界限制
            if (offsetLeft <= 0) {
                node.setPosition(cc.v2(node.width / 2 - aeraWidth / 2, node.y))
            }

            if (offsetRight >= 0) {
                node.setPosition(cc.v2(aeraWidth / 2 - node.width / 2, node.y))
            }

            if (offsetTop >= 0) {
                node.setPosition(cc.v2(node.x, aeraHieght / 2 - node.height / 2))
            }

            if (offsetButtom <= 0) {
                node.setPosition(cc.v2(node.x, node.height / 2 - aeraHieght / 2));
            }
        }

    },
    
    updateRet(data) {
        if (!data)
            return;
        if (data.code == -1) {
            //移动
           let node = this.updateOneCake(data.dataList[0],data.posList[0]);
           node.name = "cake_" + data.dataList[0].pos;
        }
        else if (data.code == 0) {
            // 交换位置
           let sNode =  this.updateOneCake(data.dataList[0],data.posList[0]);
           let tNode = this.updateOneCake(data.dataList[1],data.posList[1]);
           sNode.name = "cake_" + data.dataList[0].pos;
           tNode.name =  "cake_"  + data.dataList[1].pos
        }
        else if(data.code == 1)
        {
            //升级
            this.updateOneCake(data.dataList[0],data.posList[0],true);
            let tNode =  this.updateOneCake(data.dataList[1],data.posList[1]);
            this._updateCake(tNode,data.dataList[1]);
            tNode.name =  "cake_"  + data.dataList[1].pos
        }



    },


    updateOneCake(data,pos,isRemove = false) {
        if (!data)
            return;
        let tIndex = data.pos;
      //  cc.error()
        let node = this.gameAera.getChildByName("cake_" + pos);
        if(isRemove)
        {
            node.destroy();
            return ;
        }
        node.setPosition(this.posList[tIndex]);
        return node;
       // node.name = "cake_" + tIndex;
    },
    getCakeList() {
        let canvas = cc.director.getScene().getChildByName("Canvas");
        let mainScene = canvas.getComponent("mainScene");
        if (mainScene) {
            return mainScene.cakeList;
        }
        return null;
    },
    // 自动获取金币
    onGainCoin(data,coin = "+200"){
        let pos = data.pos;
        let cake = this.gameAera.getChildByName("cake_"+pos);
        if(!cake ) 
            return ;
        
        let  aniNode = cake.getChildByName("ani");
        let ani = aniNode.getComponent(cc.Animation);
        ani.play("coin");
        ani.active = true;
        let coinNode = cake.getChildByName("coin");
        coinNode.y = 0;
        coinNode.opacity = 255;
        let moveUp = cc.moveBy(0.5,cc.v2(0,90)).easing(cc.easeInOut(3.0));
        let fadeOut = cc.fadeOut(0.1).easing(cc.easeOut());
        this.panelBase.updateInfo(coinNode,coin,cc.Label);
        coinNode.runAction(cc.sequence(moveUp,fadeOut,cc.callFunc(()=>{
            coinNode.y = 0;
            coinNode.opacity = 255;
            //cc.log("play ani " + coinNode.y);
        })))
    },


    onDestroy() {

    },
});
